

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>nlp_architect.models.transformers.base_model &mdash; NLP Architect by Intel® AI Lab 0.5.2 documentation</title>
  

  
  
  
  

  
  <script type="text/javascript" src="../../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../../" src="../../../../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../../../../_static/jquery.js"></script>
        <script type="text/javascript" src="../../../../_static/underscore.js"></script>
        <script type="text/javascript" src="../../../../_static/doctools.js"></script>
        <script type="text/javascript" src="../../../../_static/language_data.js"></script>
        <script type="text/javascript" src="../../../../_static/install.js"></script>
        <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/nlp_arch_theme.css" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Mono" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:100,900" type="text/css" />
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../../index.html">
          

          
            
            <img src="../../../../_static/logo.png" class="logo" alt="Logo"/>
          
          </a>

          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../quick_start.html">Quick start</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../installation.html">Installation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../publications.html">Publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../tutorials.html">Jupyter Tutorials</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../model_zoo.html">Model Zoo</a></li>
</ul>
<p class="caption"><span class="caption-text">NLP/NLU Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../tagging/sequence_tagging.html">Sequence Tagging</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../sentiment.html">Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../bist_parser.html">Dependency Parsing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../intent.html">Intent Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../lm.html">Language Models</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../information_extraction.html">Information Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../transformers.html">Transformers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../archived/additional.html">Additional Models</a></li>
</ul>
<p class="caption"><span class="caption-text">Optimized Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../quantized_bert.html">Quantized BERT</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../transformers_distillation.html">Transformers Distillation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../sparse_gnmt.html">Sparse Neural Machine Translation</a></li>
</ul>
<p class="caption"><span class="caption-text">Solutions</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../absa_solution.html">Aspect Based Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../term_set_expansion.html">Set Expansion</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../trend_analysis.html">Trend Analysis</a></li>
</ul>
<p class="caption"><span class="caption-text">For Developers</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../generated_api/nlp_architect_api_index.html">nlp_architect API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../developer_guide.html">Developer Guide</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../../index.html">NLP Architect by Intel® AI Lab</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../../index.html">Module code</a> &raquo;</li>
        
          <li><a href="../../models.html">nlp_architect.models</a> &raquo;</li>
        
      <li>nlp_architect.models.transformers.base_model</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for nlp_architect.models.transformers.base_model</h1><div class="highlight"><pre>
<span></span><span class="c1"># ******************************************************************************</span>
<span class="c1"># Copyright 2017-2019 Intel Corporation</span>
<span class="c1">#</span>
<span class="c1"># Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span>
<span class="c1"># you may not use this file except in compliance with the License.</span>
<span class="c1"># You may obtain a copy of the License at</span>
<span class="c1">#</span>
<span class="c1">#     http://www.apache.org/licenses/LICENSE-2.0</span>
<span class="c1">#</span>
<span class="c1"># Unless required by applicable law or agreed to in writing, software</span>
<span class="c1"># distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span>
<span class="c1"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span>
<span class="c1"># See the License for the specific language governing permissions and</span>
<span class="c1"># limitations under the License.</span>
<span class="c1"># ******************************************************************************</span>
<span class="kn">import</span> <span class="nn">io</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Union</span>

<span class="kn">import</span> <span class="nn">torch</span>
<span class="kn">from</span> <span class="nn">torch.utils.data</span> <span class="kn">import</span> <span class="n">DataLoader</span>
<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tqdm</span><span class="p">,</span> <span class="n">trange</span>
<span class="kn">from</span> <span class="nn">transformers</span> <span class="kn">import</span> <span class="p">(</span>
    <span class="n">AdamW</span><span class="p">,</span>
    <span class="n">BertConfig</span><span class="p">,</span>
    <span class="n">BertTokenizer</span><span class="p">,</span>
    <span class="n">RobertaConfig</span><span class="p">,</span>
    <span class="n">RobertaTokenizer</span><span class="p">,</span>
    <span class="n">XLMConfig</span><span class="p">,</span>
    <span class="n">XLMTokenizer</span><span class="p">,</span>
    <span class="n">XLNetConfig</span><span class="p">,</span>
    <span class="n">XLNetTokenizer</span><span class="p">,</span>
    <span class="n">get_linear_schedule_with_warmup</span><span class="p">,</span>
<span class="p">)</span>

<span class="kn">from</span> <span class="nn">nlp_architect.models</span> <span class="kn">import</span> <span class="n">TrainableModel</span>
<span class="kn">from</span> <span class="nn">nlp_architect.models.transformers.quantized_bert</span> <span class="kn">import</span> <span class="n">QuantizedBertConfig</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>


<span class="n">ALL_MODELS</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span>
    <span class="p">(</span>
        <span class="nb">tuple</span><span class="p">(</span><span class="n">conf</span><span class="o">.</span><span class="n">pretrained_config_archive_map</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
        <span class="k">for</span> <span class="n">conf</span> <span class="ow">in</span> <span class="p">(</span><span class="n">BertConfig</span><span class="p">,</span> <span class="n">XLNetConfig</span><span class="p">,</span> <span class="n">XLMConfig</span><span class="p">)</span>
    <span class="p">),</span>
    <span class="p">(),</span>
<span class="p">)</span>


<div class="viewcode-block" id="get_models"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.get_models">[docs]</a><span class="k">def</span> <span class="nf">get_models</span><span class="p">(</span><span class="n">models</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]):</span>
    <span class="k">if</span> <span class="n">models</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">[</span><span class="n">m</span> <span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">ALL_MODELS</span> <span class="k">if</span> <span class="n">m</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;-&quot;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">in</span> <span class="n">models</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">ALL_MODELS</span></div>


<div class="viewcode-block" id="TransformerBase"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase">[docs]</a><span class="k">class</span> <span class="nc">TransformerBase</span><span class="p">(</span><span class="n">TrainableModel</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Transformers base model (for working with pytorch-transformers models)</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">MODEL_CONFIGURATIONS</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s2">&quot;bert&quot;</span><span class="p">:</span> <span class="p">(</span><span class="n">BertConfig</span><span class="p">,</span> <span class="n">BertTokenizer</span><span class="p">),</span>
        <span class="s2">&quot;quant_bert&quot;</span><span class="p">:</span> <span class="p">(</span><span class="n">QuantizedBertConfig</span><span class="p">,</span> <span class="n">BertTokenizer</span><span class="p">),</span>
        <span class="s2">&quot;xlnet&quot;</span><span class="p">:</span> <span class="p">(</span><span class="n">XLNetConfig</span><span class="p">,</span> <span class="n">XLNetTokenizer</span><span class="p">),</span>
        <span class="s2">&quot;xlm&quot;</span><span class="p">:</span> <span class="p">(</span><span class="n">XLMConfig</span><span class="p">,</span> <span class="n">XLMTokenizer</span><span class="p">),</span>
        <span class="s2">&quot;roberta&quot;</span><span class="p">:</span> <span class="p">(</span><span class="n">RobertaConfig</span><span class="p">,</span> <span class="n">RobertaTokenizer</span><span class="p">),</span>
    <span class="p">}</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">model_type</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span>
        <span class="n">model_name_or_path</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span>
        <span class="n">labels</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">num_labels</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">config_name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">tokenizer_name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">do_lower_case</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
        <span class="n">output_path</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">device</span><span class="o">=</span><span class="s2">&quot;cpu&quot;</span><span class="p">,</span>
        <span class="n">n_gpus</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Transformers base model (for working with pytorch-transformers models)</span>

<span class="sd">        Args:</span>
<span class="sd">            model_type (str): transformer model type</span>
<span class="sd">            model_name_or_path (str): model name or path to model</span>
<span class="sd">            labels (List[str], optional): list of labels. Defaults to None.</span>
<span class="sd">            num_labels (int, optional): number of labels. Defaults to None.</span>
<span class="sd">            config_name ([type], optional): configuration name. Defaults to None.</span>
<span class="sd">            tokenizer_name ([type], optional): tokenizer name. Defaults to None.</span>
<span class="sd">            do_lower_case (bool, optional): lower case input words. Defaults to False.</span>
<span class="sd">            output_path ([type], optional): model output path. Defaults to None.</span>
<span class="sd">            device (str, optional): backend device. Defaults to &#39;cpu&#39;.</span>
<span class="sd">            n_gpus (int, optional): num of gpus. Defaults to 0.</span>

<span class="sd">        Raises:</span>
<span class="sd">            FileNotFoundError: [description]</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">assert</span> <span class="n">model_type</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">MODEL_CONFIGURATIONS</span><span class="o">.</span><span class="n">keys</span><span class="p">(),</span> <span class="s2">&quot;unsupported model_type&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model_type</span> <span class="o">=</span> <span class="n">model_type</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model_name_or_path</span> <span class="o">=</span> <span class="n">model_name_or_path</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">labels</span> <span class="o">=</span> <span class="n">labels</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span> <span class="o">=</span> <span class="n">num_labels</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">do_lower_case</span> <span class="o">=</span> <span class="n">do_lower_case</span>
        <span class="k">if</span> <span class="n">output_path</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">output_path</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">FileNotFoundError</span><span class="p">(</span><span class="s2">&quot;output_path is not found&quot;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">output_path</span> <span class="o">=</span> <span class="n">output_path</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">model_class</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="n">config_class</span><span class="p">,</span> <span class="n">tokenizer_class</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">MODEL_CONFIGURATIONS</span><span class="p">[</span><span class="n">model_type</span><span class="p">]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">config_class</span> <span class="o">=</span> <span class="n">config_class</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer_class</span> <span class="o">=</span> <span class="n">tokenizer_class</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer_name</span> <span class="o">=</span> <span class="n">tokenizer_name</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_load_tokenizer</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tokenizer_name</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">config_name</span> <span class="o">=</span> <span class="n">config_name</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">config</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_load_config</span><span class="p">(</span><span class="n">config_name</span><span class="p">)</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">=</span> <span class="n">n_gpus</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">_optimizer</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_scheduler</span> <span class="o">=</span> <span class="kc">None</span>

<div class="viewcode-block" id="TransformerBase.to"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.to">[docs]</a>    <span class="k">def</span> <span class="nf">to</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">device</span><span class="o">=</span><span class="s2">&quot;cpu&quot;</span><span class="p">,</span> <span class="n">n_gpus</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="n">device</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">n_gpus</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">DataParallel</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">=</span> <span class="n">n_gpus</span></div>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">optimizer</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_optimizer</span>

    <span class="nd">@optimizer</span><span class="o">.</span><span class="n">setter</span>
    <span class="k">def</span> <span class="nf">optimizer</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">opt</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_optimizer</span> <span class="o">=</span> <span class="n">opt</span>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">scheduler</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_scheduler</span>

    <span class="nd">@scheduler</span><span class="o">.</span><span class="n">setter</span>
    <span class="k">def</span> <span class="nf">scheduler</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sch</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_scheduler</span> <span class="o">=</span> <span class="n">sch</span>

<div class="viewcode-block" id="TransformerBase.setup_default_optimizer"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.setup_default_optimizer">[docs]</a>    <span class="k">def</span> <span class="nf">setup_default_optimizer</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">weight_decay</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span><span class="p">,</span>
        <span class="n">learning_rate</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">5e-5</span><span class="p">,</span>
        <span class="n">adam_epsilon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">1e-8</span><span class="p">,</span>
        <span class="n">warmup_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
        <span class="n">total_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="c1"># Prepare optimizer and schedule (linear warmup and decay)</span>
        <span class="n">no_decay</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;bias&quot;</span><span class="p">,</span> <span class="s2">&quot;LayerNorm.weight&quot;</span><span class="p">]</span>
        <span class="n">optimizer_grouped_parameters</span> <span class="o">=</span> <span class="p">[</span>
            <span class="p">{</span>
                <span class="s2">&quot;params&quot;</span><span class="p">:</span> <span class="p">[</span>
                    <span class="n">p</span>
                    <span class="k">for</span> <span class="n">n</span><span class="p">,</span> <span class="n">p</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">named_parameters</span><span class="p">()</span>
                    <span class="k">if</span> <span class="ow">not</span> <span class="nb">any</span><span class="p">(</span><span class="n">nd</span> <span class="ow">in</span> <span class="n">n</span> <span class="k">for</span> <span class="n">nd</span> <span class="ow">in</span> <span class="n">no_decay</span><span class="p">)</span>
                <span class="p">],</span>
                <span class="s2">&quot;weight_decay&quot;</span><span class="p">:</span> <span class="n">weight_decay</span><span class="p">,</span>
            <span class="p">},</span>
            <span class="p">{</span>
                <span class="s2">&quot;params&quot;</span><span class="p">:</span> <span class="p">[</span>
                    <span class="n">p</span> <span class="k">for</span> <span class="n">n</span><span class="p">,</span> <span class="n">p</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">named_parameters</span><span class="p">()</span> <span class="k">if</span> <span class="nb">any</span><span class="p">(</span><span class="n">nd</span> <span class="ow">in</span> <span class="n">n</span> <span class="k">for</span> <span class="n">nd</span> <span class="ow">in</span> <span class="n">no_decay</span><span class="p">)</span>
                <span class="p">],</span>
                <span class="s2">&quot;weight_decay&quot;</span><span class="p">:</span> <span class="mf">0.0</span><span class="p">,</span>
            <span class="p">},</span>
        <span class="p">]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">optimizer</span> <span class="o">=</span> <span class="n">AdamW</span><span class="p">(</span><span class="n">optimizer_grouped_parameters</span><span class="p">,</span> <span class="n">lr</span><span class="o">=</span><span class="n">learning_rate</span><span class="p">,</span> <span class="n">eps</span><span class="o">=</span><span class="n">adam_epsilon</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">scheduler</span> <span class="o">=</span> <span class="n">get_linear_schedule_with_warmup</span><span class="p">(</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">optimizer</span><span class="p">,</span> <span class="n">num_warmup_steps</span><span class="o">=</span><span class="n">warmup_steps</span><span class="p">,</span> <span class="n">num_training_steps</span><span class="o">=</span><span class="n">total_steps</span>
        <span class="p">)</span></div>

    <span class="k">def</span> <span class="nf">_load_config</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">config_name</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="n">config</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">config_class</span><span class="o">.</span><span class="n">from_pretrained</span><span class="p">(</span>
            <span class="n">config_name</span> <span class="k">if</span> <span class="n">config_name</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_name_or_path</span><span class="p">,</span> <span class="n">num_labels</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">num_labels</span>
        <span class="p">)</span>
        <span class="k">return</span> <span class="n">config</span>

    <span class="k">def</span> <span class="nf">_load_tokenizer</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tokenizer_name</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="n">tokenizer</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer_class</span><span class="o">.</span><span class="n">from_pretrained</span><span class="p">(</span>
            <span class="n">tokenizer_name</span> <span class="k">if</span> <span class="n">tokenizer_name</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_name_or_path</span><span class="p">,</span>
            <span class="n">do_lower_case</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">do_lower_case</span><span class="p">,</span>
        <span class="p">)</span>
        <span class="k">return</span> <span class="n">tokenizer</span>

<div class="viewcode-block" id="TransformerBase.save_model"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.save_model">[docs]</a>    <span class="k">def</span> <span class="nf">save_model</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">output_dir</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">save_checkpoint</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Save model/tokenizer/arguments to given output directory</span>

<span class="sd">        Args:</span>
<span class="sd">            output_dir (str): path to output directory</span>
<span class="sd">            save_checkpoint (bool, optional): save as checkpoint. Defaults to False.</span>
<span class="sd">            args ([type], optional): arguments object to save. Defaults to None.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="c1"># Create output directory if needed</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">output_dir</span><span class="p">):</span>
            <span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">output_dir</span><span class="p">)</span>

        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;Saving model checkpoint to </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">output_dir</span><span class="p">)</span>
        <span class="n">model_to_save</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">module</span> <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="s2">&quot;module&quot;</span><span class="p">)</span> <span class="k">else</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span>
        <span class="n">model_to_save</span><span class="o">.</span><span class="n">save_pretrained</span><span class="p">(</span><span class="n">output_dir</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">save_checkpoint</span><span class="p">:</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">tokenizer</span><span class="o">.</span><span class="n">save_pretrained</span><span class="p">(</span><span class="n">output_dir</span><span class="p">)</span>
            <span class="k">with</span> <span class="n">io</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">output_dir</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;labels.txt&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fw</span><span class="p">:</span>
                <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">labels</span><span class="p">:</span>
                    <span class="n">fw</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{}</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">l</span><span class="p">))</span>
            <span class="k">if</span> <span class="n">args</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
                <span class="n">torch</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">output_dir</span><span class="p">,</span> <span class="s2">&quot;training_args.bin&quot;</span><span class="p">))</span></div>

<div class="viewcode-block" id="TransformerBase.load_model"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.load_model">[docs]</a>    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">load_model</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">model_path</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">model_type</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Create a TranformerBase deom from given path</span>

<span class="sd">        Args:</span>
<span class="sd">            model_path (str): path to model</span>
<span class="sd">            model_type (str): model type</span>

<span class="sd">        Returns:</span>
<span class="sd">            TransformerBase: model</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="c1"># Load a trained model and vocabulary from given path</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">model_path</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">FileNotFoundError</span>
        <span class="k">with</span> <span class="n">io</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">model_path</span> <span class="o">+</span> <span class="n">os</span><span class="o">.</span><span class="n">sep</span> <span class="o">+</span> <span class="s2">&quot;labels.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
            <span class="n">labels</span> <span class="o">=</span> <span class="p">[</span><span class="n">l</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="n">fp</span><span class="o">.</span><span class="n">readlines</span><span class="p">()]</span>
        <span class="k">return</span> <span class="bp">cls</span><span class="p">(</span>
            <span class="n">model_type</span><span class="o">=</span><span class="n">model_type</span><span class="p">,</span> <span class="n">model_name_or_path</span><span class="o">=</span><span class="n">model_path</span><span class="p">,</span> <span class="n">labels</span><span class="o">=</span><span class="n">labels</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span>
        <span class="p">)</span></div>

<div class="viewcode-block" id="TransformerBase.get_train_steps_epochs"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.get_train_steps_epochs">[docs]</a>    <span class="nd">@staticmethod</span>
    <span class="k">def</span> <span class="nf">get_train_steps_epochs</span><span class="p">(</span>
        <span class="n">max_steps</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">num_train_epochs</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">gradient_accumulation_steps</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">num_samples</span><span class="p">:</span> <span class="nb">int</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        get train steps and epochs</span>

<span class="sd">        Args:</span>
<span class="sd">            max_steps (int): max steps</span>
<span class="sd">            num_train_epochs (int): num epochs</span>
<span class="sd">            gradient_accumulation_steps (int): gradient accumulation steps</span>
<span class="sd">            num_samples (int): number of samples</span>

<span class="sd">        Returns:</span>
<span class="sd">            Tuple: total steps, number of epochs</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="n">max_steps</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">t_total</span> <span class="o">=</span> <span class="n">max_steps</span>
            <span class="n">num_train_epochs</span> <span class="o">=</span> <span class="n">max_steps</span> <span class="o">//</span> <span class="p">(</span><span class="n">num_samples</span> <span class="o">//</span> <span class="n">gradient_accumulation_steps</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">t_total</span> <span class="o">=</span> <span class="n">num_samples</span> <span class="o">//</span> <span class="n">gradient_accumulation_steps</span> <span class="o">*</span> <span class="n">num_train_epochs</span>
        <span class="k">return</span> <span class="n">t_total</span><span class="p">,</span> <span class="n">num_train_epochs</span></div>

<div class="viewcode-block" id="TransformerBase.get_logits"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.get_logits">[docs]</a>    <span class="k">def</span> <span class="nf">get_logits</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">batch</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">eval</span><span class="p">()</span>
        <span class="n">inputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_batch_mapper</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
        <span class="n">outputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">outputs</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span></div>

    <span class="k">def</span> <span class="nf">_train</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">data_set</span><span class="p">:</span> <span class="n">DataLoader</span><span class="p">,</span>
        <span class="n">dev_data_set</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">,</span> <span class="n">List</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">]]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">test_data_set</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">,</span> <span class="n">List</span><span class="p">[</span><span class="n">DataLoader</span><span class="p">]]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">gradient_accumulation_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
        <span class="n">per_gpu_train_batch_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">8</span><span class="p">,</span>
        <span class="n">max_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span>
        <span class="n">num_train_epochs</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span>
        <span class="n">max_grad_norm</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">1.0</span><span class="p">,</span>
        <span class="n">logging_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span>
        <span class="n">save_steps</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">100</span><span class="p">,</span>
    <span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Run model training</span>
<span class="sd">            batch_mapper: a function that maps a batch into parameters that the model</span>
<span class="sd">                          expects in the forward method (for use with custom heads and models).</span>
<span class="sd">                          If None it will default to the basic models input structure.</span>
<span class="sd">            logging_callback_fn: a function that is called in each evaluation step</span>
<span class="sd">                          with the model as a parameter.</span>

<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">t_total</span><span class="p">,</span> <span class="n">num_train_epochs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_train_steps_epochs</span><span class="p">(</span>
            <span class="n">max_steps</span><span class="p">,</span> <span class="n">num_train_epochs</span><span class="p">,</span> <span class="n">gradient_accumulation_steps</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">data_set</span><span class="p">)</span>
        <span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">optimizer</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">scheduler</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;Loading default optimizer and scheduler&quot;</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">setup_default_optimizer</span><span class="p">(</span><span class="n">total_steps</span><span class="o">=</span><span class="n">t_total</span><span class="p">)</span>

        <span class="n">train_batch_size</span> <span class="o">=</span> <span class="n">per_gpu_train_batch_size</span> <span class="o">*</span> <span class="nb">max</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;***** Running training *****&quot;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Num examples = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">data_set</span><span class="o">.</span><span class="n">dataset</span><span class="p">))</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Num Epochs = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">num_train_epochs</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Instantaneous batch size per GPU/CPU = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">per_gpu_train_batch_size</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span>
            <span class="s2">&quot;  Total train batch size (w. parallel, distributed &amp; accumulation) = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span>
            <span class="n">train_batch_size</span> <span class="o">*</span> <span class="n">gradient_accumulation_steps</span><span class="p">,</span>
        <span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Gradient Accumulation steps = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">gradient_accumulation_steps</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;  Total optimization steps = </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">t_total</span><span class="p">)</span>

        <span class="n">global_step</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">tr_loss</span><span class="p">,</span> <span class="n">logging_loss</span> <span class="o">=</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span>
        <span class="n">train_iterator</span> <span class="o">=</span> <span class="n">trange</span><span class="p">(</span><span class="n">num_train_epochs</span><span class="p">,</span> <span class="n">desc</span><span class="o">=</span><span class="s2">&quot;Epoch&quot;</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="n">train_iterator</span><span class="p">:</span>
            <span class="n">epoch_iterator</span> <span class="o">=</span> <span class="n">tqdm</span><span class="p">(</span><span class="n">data_set</span><span class="p">,</span> <span class="n">desc</span><span class="o">=</span><span class="s2">&quot;Train iteration&quot;</span><span class="p">)</span>
            <span class="k">for</span> <span class="n">step</span><span class="p">,</span> <span class="n">batch</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">epoch_iterator</span><span class="p">):</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">train</span><span class="p">()</span>
                <span class="n">batch</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">batch</span><span class="p">)</span>
                <span class="n">inputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_batch_mapper</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
                <span class="n">outputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs</span><span class="p">)</span>
                <span class="n">loss</span> <span class="o">=</span> <span class="n">outputs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>  <span class="c1"># get loss</span>

                <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">n_gpus</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                    <span class="n">loss</span> <span class="o">=</span> <span class="n">loss</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>  <span class="c1"># mean() to average on multi-gpu parallel training</span>
                <span class="k">if</span> <span class="n">gradient_accumulation_steps</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                    <span class="n">loss</span> <span class="o">=</span> <span class="n">loss</span> <span class="o">/</span> <span class="n">gradient_accumulation_steps</span>

                <span class="n">loss</span><span class="o">.</span><span class="n">backward</span><span class="p">()</span>
                <span class="n">torch</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">clip_grad_norm_</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">parameters</span><span class="p">(),</span> <span class="n">max_grad_norm</span><span class="p">)</span>

                <span class="n">tr_loss</span> <span class="o">+=</span> <span class="n">loss</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
                <span class="k">if</span> <span class="p">(</span><span class="n">step</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">%</span> <span class="n">gradient_accumulation_steps</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">optimizer</span><span class="o">.</span><span class="n">step</span><span class="p">()</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">scheduler</span><span class="o">.</span><span class="n">step</span><span class="p">()</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span>
                    <span class="n">global_step</span> <span class="o">+=</span> <span class="mi">1</span>

                    <span class="k">if</span> <span class="n">logging_steps</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="ow">and</span> <span class="n">global_step</span> <span class="o">%</span> <span class="n">logging_steps</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                        <span class="c1"># Log metrics and run evaluation on dev/test</span>
                        <span class="k">for</span> <span class="n">ds</span> <span class="ow">in</span> <span class="p">[</span><span class="n">dev_data_set</span><span class="p">,</span> <span class="n">test_data_set</span><span class="p">]:</span>
                            <span class="k">if</span> <span class="n">ds</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>  <span class="c1"># got no data loader</span>
                                <span class="k">continue</span>
                            <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">DataLoader</span><span class="p">):</span>
                                <span class="n">ds</span> <span class="o">=</span> <span class="p">[</span><span class="n">ds</span><span class="p">]</span>
                            <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">ds</span><span class="p">:</span>
                                <span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_evaluate</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
                                <span class="bp">self</span><span class="o">.</span><span class="n">evaluate_predictions</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">)</span>
                        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;lr = </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">scheduler</span><span class="o">.</span><span class="n">get_lr</span><span class="p">()[</span><span class="mi">0</span><span class="p">]))</span>
                        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;loss = </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">((</span><span class="n">tr_loss</span> <span class="o">-</span> <span class="n">logging_loss</span><span class="p">)</span> <span class="o">/</span> <span class="n">logging_steps</span><span class="p">))</span>
                        <span class="n">logging_loss</span> <span class="o">=</span> <span class="n">tr_loss</span>

                    <span class="k">if</span> <span class="n">save_steps</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="ow">and</span> <span class="n">global_step</span> <span class="o">%</span> <span class="n">save_steps</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                        <span class="c1"># Save model checkpoint</span>
                        <span class="bp">self</span><span class="o">.</span><span class="n">save_model_checkpoint</span><span class="p">(</span>
                            <span class="n">output_path</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">output_path</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s2">&quot;checkpoint-</span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">global_step</span><span class="p">)</span>
                        <span class="p">)</span>

                <span class="k">if</span> <span class="mi">0</span> <span class="o">&lt;</span> <span class="n">max_steps</span> <span class="o">&lt;</span> <span class="n">global_step</span><span class="p">:</span>
                    <span class="n">epoch_iterator</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
                    <span class="k">break</span>
            <span class="k">if</span> <span class="mi">0</span> <span class="o">&lt;</span> <span class="n">max_steps</span> <span class="o">&lt;</span> <span class="n">global_step</span><span class="p">:</span>
                <span class="n">train_iterator</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
                <span class="k">break</span>

        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot; global_step = </span><span class="si">%s</span><span class="s2">, average loss = </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">global_step</span><span class="p">,</span> <span class="n">tr_loss</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_evaluate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data_set</span><span class="p">:</span> <span class="n">DataLoader</span><span class="p">):</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot;***** Running inference *****&quot;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&quot; Batch size: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">data_set</span><span class="o">.</span><span class="n">batch_size</span><span class="p">))</span>
        <span class="n">eval_loss</span> <span class="o">=</span> <span class="mf">0.0</span>
        <span class="n">nb_eval_steps</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="n">preds</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="n">out_label_ids</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">for</span> <span class="n">batch</span> <span class="ow">in</span> <span class="n">tqdm</span><span class="p">(</span><span class="n">data_set</span><span class="p">,</span> <span class="n">desc</span><span class="o">=</span><span class="s2">&quot;Inference iteration&quot;</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">eval</span><span class="p">()</span>
            <span class="n">batch</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">to</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">device</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">batch</span><span class="p">)</span>

            <span class="k">with</span> <span class="n">torch</span><span class="o">.</span><span class="n">no_grad</span><span class="p">():</span>
                <span class="n">inputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_batch_mapper</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
                <span class="n">outputs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">inputs</span><span class="p">)</span>
                <span class="k">if</span> <span class="s2">&quot;labels&quot;</span> <span class="ow">in</span> <span class="n">inputs</span><span class="p">:</span>
                    <span class="n">tmp_eval_loss</span><span class="p">,</span> <span class="n">logits</span> <span class="o">=</span> <span class="n">outputs</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>
                    <span class="n">eval_loss</span> <span class="o">+=</span> <span class="n">tmp_eval_loss</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span><span class="o">.</span><span class="n">item</span><span class="p">()</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">logits</span> <span class="o">=</span> <span class="n">outputs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
            <span class="n">nb_eval_steps</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="n">model_output</span> <span class="o">=</span> <span class="n">logits</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span>
            <span class="n">model_out_label_ids</span> <span class="o">=</span> <span class="n">inputs</span><span class="p">[</span><span class="s2">&quot;labels&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">detach</span><span class="p">()</span><span class="o">.</span><span class="n">cpu</span><span class="p">()</span> <span class="k">if</span> <span class="s2">&quot;labels&quot;</span> <span class="ow">in</span> <span class="n">inputs</span> <span class="k">else</span> <span class="kc">None</span>
            <span class="k">if</span> <span class="n">preds</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
                <span class="n">preds</span> <span class="o">=</span> <span class="n">model_output</span>
                <span class="n">out_label_ids</span> <span class="o">=</span> <span class="n">model_out_label_ids</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">preds</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">cat</span><span class="p">((</span><span class="n">preds</span><span class="p">,</span> <span class="n">model_output</span><span class="p">),</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
                <span class="n">out_label_ids</span> <span class="o">=</span> <span class="p">(</span>
                    <span class="n">torch</span><span class="o">.</span><span class="n">cat</span><span class="p">((</span><span class="n">out_label_ids</span><span class="p">,</span> <span class="n">model_out_label_ids</span><span class="p">),</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
                    <span class="k">if</span> <span class="n">out_label_ids</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
                    <span class="k">else</span> <span class="kc">None</span>
                <span class="p">)</span>
        <span class="k">if</span> <span class="n">out_label_ids</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">preds</span>
        <span class="k">return</span> <span class="n">preds</span><span class="p">,</span> <span class="n">out_label_ids</span>

    <span class="k">def</span> <span class="nf">_batch_mapper</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">batch</span><span class="p">):</span>
        <span class="n">mapping</span> <span class="o">=</span> <span class="p">{</span>
            <span class="s2">&quot;input_ids&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span>
            <span class="s2">&quot;attention_mask&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span>
            <span class="c1"># XLM don&#39;t use segment_ids</span>
            <span class="s2">&quot;token_type_ids&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">model_type</span> <span class="ow">in</span> <span class="p">[</span><span class="s2">&quot;bert&quot;</span><span class="p">,</span> <span class="s2">&quot;quant_bert&quot;</span><span class="p">,</span> <span class="s2">&quot;xlnet&quot;</span><span class="p">]</span>
            <span class="k">else</span> <span class="kc">None</span><span class="p">,</span>
        <span class="p">}</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span> <span class="o">==</span> <span class="mi">4</span><span class="p">:</span>
            <span class="n">mapping</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s2">&quot;labels&quot;</span><span class="p">:</span> <span class="n">batch</span><span class="p">[</span><span class="mi">3</span><span class="p">]})</span>
        <span class="k">return</span> <span class="n">mapping</span>

<div class="viewcode-block" id="TransformerBase.evaluate_predictions"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.evaluate_predictions">[docs]</a>    <span class="k">def</span> <span class="nf">evaluate_predictions</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">logits</span><span class="p">,</span> <span class="n">label_ids</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span>
            <span class="s2">&quot;evaluate_predictions method must be implemented in order to&quot;</span>
            <span class="s2">&quot;be used for dev/test set evaluation&quot;</span>
        <span class="p">)</span></div>

<div class="viewcode-block" id="TransformerBase.save_model_checkpoint"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.TransformerBase.save_model_checkpoint">[docs]</a>    <span class="k">def</span> <span class="nf">save_model_checkpoint</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">output_path</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">name</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        save model checkpoint</span>

<span class="sd">        Args:</span>
<span class="sd">            output_path (str): output path</span>
<span class="sd">            name (str): name of checkpoint</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">output_dir_path</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">output_path</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">save_model</span><span class="p">(</span><span class="n">output_dir_path</span><span class="p">,</span> <span class="n">save_checkpoint</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span></div></div>


<div class="viewcode-block" id="InputFeatures"><a class="viewcode-back" href="../../../../generated_api/nlp_architect.models.transformers.html#nlp_architect.models.transformers.base_model.InputFeatures">[docs]</a><span class="k">class</span> <span class="nc">InputFeatures</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;A single set of features of data.&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">input_ids</span><span class="p">,</span> <span class="n">input_mask</span><span class="p">,</span> <span class="n">segment_ids</span><span class="p">,</span> <span class="n">label_id</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">valid_ids</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">input_ids</span> <span class="o">=</span> <span class="n">input_ids</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">input_mask</span> <span class="o">=</span> <span class="n">input_mask</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">segment_ids</span> <span class="o">=</span> <span class="n">segment_ids</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">label_id</span> <span class="o">=</span> <span class="n">label_id</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">valid_ids</span> <span class="o">=</span> <span class="n">valid_ids</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>